const formatDate = function(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  const o = {

    'M+': date.getMonth() + 1,

    'd+': date.getDate(),

    'h+': date.getHours(),

    'm+': date.getMinutes(),

    's+': date.getSeconds()

  }

  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''

      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }

  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

/**
 * 日期字符串转化日期对象
 * @param str
 * @returns {Date}
 */
const getDate = function(str) {
  if (/^\d+$/.test(str)) {
    // 纯数字字符串
    return new Date(Number(str))
  } else if (str && typeof str === 'string') {
    return new Date(str.replace(/-/g, '/'))
  } else {
    return new Date(str)
  }
}

/**
 * 处理time
 * @param time 2018-11-25 00:00:00 格式
 * @param type
 * @returns {number}
 */
const getTimeListIndex = function(time, type, timeList) {
  let index, endId, hour
  const minute = time.slice(11).split(':') && time.slice(11).split(':')[1]
  endId = minute < 30 ? '00' : '30'
  hour = time.slice(11, 13)
  const realTimeId = parseInt(hour + endId)
  if (parseInt(realTimeId) < 800) {
    index = 0
  } else if (parseInt(realTimeId) >= 1900) {
    index = 23
  } else {
    index = timeList.findIndex(function(value) {
      return value.gridId == realTimeId
    })
    if (type === 'end') {
      if (minute === '00' || minute === '30') {
        index = index - 1
      }
    }
  }
  return index
}

const getCurrentMonth = function(){
  var date = new Date();
  // 获取当前月份
  var nowMonth = date.getMonth() + 1;
  // 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }
  return date.getFullYear() + "" + nowMonth;
}

export {
  formatDate,
  getDate,
  getTimeListIndex,
  getCurrentMonth
}

